# -*- coding:utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.http import HttpResponseRedirect
from wenlincms.utils.urls import admin_url

from wlapps.wlcore.models import Region, Region_fields, SiteSetting, SiteSetting_fields, DevSetting, DevSetting_fields


class RegionAdmin(admin.ModelAdmin):
    fieldsets = ((None, {"fields": Region_fields}),)
    list_display = ["id", "code", "level", "title", "get_parent", "fulltitle", "allparents"]
    list_filter = ["level"]
    search_fields = ["title", ]
    raw_id_fields = ("parent",)
    ordering = ["id"]

    def get_actions(self, request):
        actions = super(RegionAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def get_parent(self, obj):
        return obj.parent.title

    get_parent.short_description = '上级地区'
    get_parent.admin_order_field = 'parent__title'


class AdminLogAdmin(admin.ModelAdmin):
    fieldsets = ((None, {"fields": ['user', 'content_type', 'object_repr', 'action_flag', 'change_message']}),)
    list_display = ['id', 'action_time', 'user', 'content_type', 'object_repr', 'action_flag', 'change_message']
    list_filter = ['user', ]
    search_fields = ['change_message']
    raw_id_fields = ('user',)
    readonly_fields = ('user', 'content_type', 'object_repr', 'action_flag', 'change_message')

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(AdminLogAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions


LogEntry._meta.get_field('content_type').verbose_name = '对象类型'
LogEntry._meta.get_field('object_repr').verbose_name = '标题'
LogEntry._meta.verbose_name = '后台日志'
LogEntry._meta.verbose_name_plural = '后台日志'


class SiteSettingAdmin(admin.ModelAdmin):
    fieldsets = ((None, {"fields": SiteSetting_fields[:4]}),
                 (None, {"fields": SiteSetting_fields[4:]}),)

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(SiteSettingAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def changelist_view(self, *args, **kwargs):
        objs = SiteSetting.objects.all()
        if len(objs):
            obj = objs[0]
        else:
            obj = SiteSetting()
            obj.save()
        return HttpResponseRedirect(admin_url(SiteSetting, "change", object_id=obj.id))


class DevSettingAdmin(admin.ModelAdmin):
    fieldsets = ((None, {"fields": DevSetting_fields[:6]}),
                 ("邮件服务", {"fields": DevSetting_fields[6:10]}),
                 ("短信服务", {"fields": DevSetting_fields[10:]}),)
    radio_fields = {"DEBUG": admin.HORIZONTAL}

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(DevSettingAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def changelist_view(self, *args, **kwargs):
        objs = DevSetting.objects.all()
        if len(objs):
            obj = objs[0]
        else:
            obj = DevSetting()
            obj.save()
        return HttpResponseRedirect(admin_url(DevSetting, "change", object_id=obj.id))

    def get_object(self, request, object_id):
        from mainsys.config import DEBUG, ALLOWED_HOSTS, WL_THEME, CACHE_MIDDLEWARE_SECONDS, \
            CACHE_MIDDLEWARE_KEY_PREFIX, FILE_UPLOAD_MAX_MEMORY_SIZE, EMAIL_HOST, \
            EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_PORT, SM_OPTIONS
        objs = DevSetting.objects.all()
        if len(objs):
            obj = objs[0]
        else:
            obj = DevSetting()
            obj.save()
        obj.DEBUG = DEBUG
        obj.ALLOWED_HOSTS = ", ".join(ALLOWED_HOSTS)
        obj.WL_THEME = WL_THEME
        obj.CACHE_MIDDLEWARE_SECONDS = CACHE_MIDDLEWARE_SECONDS
        obj.CACHE_MIDDLEWARE_KEY_PREFIX = CACHE_MIDDLEWARE_KEY_PREFIX
        obj.FILE_UPLOAD_MAX_MEMORY_SIZE = FILE_UPLOAD_MAX_MEMORY_SIZE
        obj.EMAIL_HOST = EMAIL_HOST
        obj.EMAIL_PORT = EMAIL_PORT
        obj.EMAIL_HOST_USER = EMAIL_HOST_USER
        obj.EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
        obj.SM_ACCOUNTSID = SM_OPTIONS["ACCOUNTSID"]
        obj.SM_ACCOUNTTOKEN = SM_OPTIONS["ACCOUNTTOKEN"]
        obj.SM_APPID = SM_OPTIONS["APPID"]
        obj.SM_SERVERIP = SM_OPTIONS["SERVERIP"]
        obj.SM_SERVERPORT = SM_OPTIONS["SERVERPORT"]
        obj.SM_SOFTVERSION = SM_OPTIONS["SOFTVERSION"]
        return obj


# 根据settings中的设置，动态启用地区的后台管理
try:
    from mainsys.settings import Region_ADMIN_ENABLE

    if Region_ADMIN_ENABLE:
        admin.site.register(Region, RegionAdmin)
except ImportError:
    pass
admin.site.register(LogEntry, AdminLogAdmin)
admin.site.register(SiteSetting, SiteSettingAdmin)
admin.site.register(DevSetting, DevSettingAdmin)
